/*
	   _           _      _           _     _ 
	  (_)         | |    | |         (_)   | |
	   _ _   _ ___| |_ __| |_ __ ___  _  __| |
	  | | | | / __| __/ _` | '__/ _ \| |/ _` |
	  | | |_| \__ \ || (_| | | | (_) | | (_| |
	  | |\__,_|___/\__\__,_|_|  \___/|_|\__,_|
	 _/ |                                     
	|__/ 
	
	Copyright 2013 Caspar Isemer and and Eva Krueger, http://justdroid.org	
	
	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at
	
		http://www.apache.org/licenses/LICENSE-2.0
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License. 
*/

package org.justdroid.justdroid;

import java.util.ArrayList;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

public class TextMessagesComposerRecipientApp extends JustDroidActivity {
	
	private Button btnProceed;
	private EditText editRecipient;
	private ListView namesListView;
	private ArrayList<String> name, type, contactId, number;
	private ContactsAdapter adapter;
	private int currentSelection = -1;
	
	void proceed() {
		Intent intent = new Intent(getApplicationContext(), TextMessagesComposerApp.class);	 				
		intent.putExtra("number", editRecipient.getText().toString());
		startActivity(intent);
	}

	void attachKeyListener(Button button) {
		button.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
				if(keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
					switch(keyCode) {
					case KeyEvent.KEYCODE_DPAD_CENTER:
					case KeyEvent.KEYCODE_ENTER:
						proceed();
						break;
					}
				}
				return false;
			}
		});
	}
	
	void startNewActivity(String name, String type, String number) {
		Intent intent = new Intent(getApplicationContext(), TextMessagesComposerApp.class);
		intent.putExtra("name", name);
		intent.putExtra("type", type);
		intent.putExtra("number", number);
		startActivity(intent);
	}
	
	/** Create the Text Messages Composer activity **/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.textmessages_composer_recipient);
		super.onCreate(savedInstanceState);
		
		// Currently, do not know how to write the code that implements text message sending
		// The picking of contacts should be similar to how it would work in ContactsApp.java
		
		/** Find UI elements **/
		btnProceed = (Button) findViewById(R.id.btnProceed);
	    editRecipient = (EditText) findViewById(R.id.inputTextMessagesRecipient);
	    namesListView = (ListView) findViewById(R.id.lstNames);
		
	    attachListener(btnProceed);
	    
	    btnProceed.setVisibility(View.GONE);
	    
		/** If Send button is pressed, send the text message to the selected recipient **/
	    btnProceed.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View v) {
	        	 proceed();
	        }
	    });
	    
	   /* namesListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long arg3) {
				giveFeedback(((TextView)view).getText().toString());
			}
		});*/
	    
	    namesListView.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long arg3) {
				if(contactId.size() == 0) {
					startNewActivity(name.get(position).toString(), type.get(position).toString(), number.get(position).toString());
				}
				else {
					startNewActivity(name.get(position).toString(), type.get(position).toString(), number.get(position).toString());
				}
			}
		});
	    
	    namesListView.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
				ListView lstView = (ListView) view;
				if(keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
					switch(keyCode) {
					case KeyEvent.KEYCODE_DPAD_CENTER:
					case KeyEvent.KEYCODE_ENTER:
						if(contactId.size() == 0) {
							startNewActivity(name.get(currentSelection).toString(), type.get(currentSelection).toString(), number.get(currentSelection).toString());
						}
						else {
							startNewActivity(name.get(currentSelection).toString(), type.get(currentSelection).toString(), number.get(currentSelection).toString());
						}
						break;
					case KeyEvent.KEYCODE_DPAD_DOWN:
						currentSelection++;
						if(currentSelection == lstView.getCount()) {
							currentSelection = 0;
						}
						else {
							giveFeedback(namesListView.getItemAtPosition(currentSelection).toString());
							lstView.setSelection(currentSelection);
						}
						break;
					case KeyEvent.KEYCODE_DPAD_UP:
						currentSelection--;
						if(currentSelection == -1) {
							currentSelection = namesListView.getCount() - 1;
						}
						else {
							giveFeedback(namesListView.getItemAtPosition(currentSelection).toString());
							lstView.setSelection(currentSelection);
						}
						break;
					}
				}
				return false;
			}
		});
	    
	    editRecipient.addTextChangedListener(new TextWatcher() {

            @SuppressLint("DefaultLocale")
			@Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                    int arg3) {
            	if(Utils.isAccessibilityEnabled(getApplicationContext()))
            		TTS.speak(TTS.readNumber(cs.toString()));
            	ArrayList<String> arrayListToBeDisplayed = new ArrayList<String>();
            	//check if user entered a letter
            	if(!(editRecipient.getText().toString().trim().equals("")) && !(editRecipient.getText().toString().matches("-?\\d+(\\.\\d+)?"))) {
            		btnProceed.setVisibility(View.GONE);
	            	//search if name exists in contacts
            		HashMap<String, ArrayList<String>> listOfNames = new ContactManager(getApplicationContext()).getNamesStartingWith(editRecipient.getText().toString());
            		name = new ArrayList<String>();
            		contactId = new ArrayList<String>();
            		type = new ArrayList<String>();
            		number = new ArrayList<String>();
            		
            		for(int i=0; i<((ArrayList<String>)(listOfNames.get("name"))).size(); i++) {
            			if(!contactId.contains(((ArrayList<String>)(listOfNames.get("id"))).get(i).toString())) 
            			{
            				name.add(((ArrayList<String>)(listOfNames.get("name"))).get(i).toString());
            				contactId.add(((ArrayList<String>)(listOfNames.get("id"))).get(i).toString());
            				type.add(((ArrayList<String>)(listOfNames.get("type"))).get(i).toString());
            				arrayListToBeDisplayed.add(name.get(name.size()-1) + " " + type.get(type.size()-1));
            			}
            		}
            		
            	}
            	else {
            		if(!(editRecipient.getText().toString().trim().equals(""))) {
	            		//user entered a number
	            		btnProceed.setVisibility(View.VISIBLE);
	            		//search if number exists in contacts
	            		HashMap<String, ArrayList<String>> listOfNames = new ContactManager(getApplicationContext()).getNamesWithNumber(editRecipient.getText().toString());
	            		name = new ArrayList<String>();
	            		number = new ArrayList<String>();
	            		type = new ArrayList<String>();
	            		contactId = new ArrayList<String>();
	            		for(int i=0; i<((ArrayList<String>)(listOfNames.get("name"))).size(); i++) {
	            			if(!number.contains(((ArrayList<String>)(listOfNames.get("number"))).get(i).toString())) 
	            			{
	            				name.add(((ArrayList<String>)(listOfNames.get("name"))).get(i).toString());
	            				number.add(((ArrayList<String>)(listOfNames.get("number"))).get(i).toString());
	            				type.add(((ArrayList<String>)(listOfNames.get("type"))).get(i).toString());
	            				contactId.add(((ArrayList<String>)(listOfNames.get("id"))).get(i).toString());
	            				arrayListToBeDisplayed.add(name.get(name.size()-1) + " " + type.get(type.size()-1));
	            			}
	            		}
	            	}
            		else {
            			//empty input
            			btnProceed.setVisibility(View.GONE);
            		}
            	}
            	adapter = new ContactsAdapter(getApplicationContext(), arrayListToBeDisplayed);
            	namesListView.setAdapter(adapter);           	
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                    int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable arg0) {

            }
        });
		/** Put most everything before here **/
	}	
	
	@Override
	public void onResume() {
		super.onResume();
		//get the root layout
		LinearLayout layout = (LinearLayout) findViewById(R.id.textmessagescomposer);
		Utils.applyFontColorChanges(getApplicationContext(), layout);  Utils.applyFontSizeChanges(getApplicationContext(), layout);  Utils.applyFontTypeChanges(getApplicationContext(), layout);
	}
}
